import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import * as accountService from '@/services/account';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    code: undefined,
    msg: undefined
  },

  effects: {
    *login({ payload }, { call, put }) {
      console.log("Login");
      console.log(payload);
      const response = yield call(accountService.login, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      console.log(response)
      if (response.code === 200) {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          console.log(`1:+${redirect}`)
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            console.log(`2:+${redirect}`)
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
              console.log(`3:+${redirect}`)
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },
    *logout(_, { call, put }) {
      console.log("Logout");
      const response = yield call(accountService.logout);
      console.log(response)
      yield put({
        type: 'changeLoginStatus',
        payload: {
          code: 200,
          msg: "注销成功",
          data: {
            currentAuthority: 'guest'
          }
        },
      });
      if (response.code === 200) {
        reloadAuthorized();
        yield put(
          routerRedux.push({
            pathname: '/user/login',
            // 下面会有问题，当多个request401时 触发多次拼接 导致登录有问题
            // search: stringify({
            //   redirect: window.location.href,
            // }),
          })
        );
      }
    },


  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.data.currentAuthority);
      return {
        ...state,
        code: payload.code,
        msg: payload.msg
      };
    },
  },
};
